
import 'package:shared_preferences/shared_preferences.dart';

class SPUtils {
  static saveData(String key, dynamic value) async {
    final sp = await SharedPreferences.getInstance();

    if (value != null) {
      switch (value.runtimeType) {
        case (const (double)):
          sp.setDouble(key, value);
          break;
        case (const (String)):
          sp.setString(key, value);
          break;
        case (const (int)):
          sp.setInt(key, value);
          break;
        case (const (bool)):
          sp.setBool(key, value);
          break;
        case const (List<String>):
          sp.setStringList(key, value);
          break;
      }
    } else {
      sp.setString(key, "");
    }
  }

  static Future<double> getDataDouble(String key) async {
    final sp = await SharedPreferences.getInstance();
    return sp.getDouble(key) ?? 0.0;
  }

  static Future<String> getDataString(String key) async {
    final sp = await SharedPreferences.getInstance();
    return sp.getString(key) ?? "";
  }

  static Future<int> getDataInt(String key) async {
    final sp = await SharedPreferences.getInstance();
    return sp.getInt(key) ?? 0;
  }

  static Future<bool> getDataBool(String key) async {
    final sp = await SharedPreferences.getInstance();
    return sp.getBool(key) ?? false;
  }

  static Future<List<String>?> getDataListString(String key) async {
    final sp = await SharedPreferences.getInstance();
    return sp.getStringList(key);
  }

  //单个删除
  static Future<bool> remove(String key) async {
    final sp = await SharedPreferences.getInstance();
    bool success = await sp.remove(key);
    return success;
  }

  //全部删除
  static clearAll() async {
    final sp = await SharedPreferences.getInstance();
    await sp.clear();
  }
}